<?php
class Backend_Designer_Sub_Fs extends Backend_Designer_Sub
{
	/**
	 * Designer config
	 * @var Config_File_Array
	 */
	protected $_config;
	
	protected $_module = 'Designer';
	 
	/**
	 * Files list
	 */
	public function fslistAction()
	{
		$path = Request::post('node', 'string', '');
		$path = str_replace('.','', $path);
			
		$dirPath = $this->_config->get('configs');
				
		if(!is_dir($dirPath))
			Response::jsonArray(array());
			
		$files = File::scanFiles($dirPath . $path, array('.dat') , false , File::Files_Dirs);
		
		if(empty($files))
			Response::jsonArray(array());
			
		$list = array();

		foreach($files as $k=>$fpath)
		{
			$text  = basename($fpath);
		
			$obj = new stdClass();
			$obj->id =str_replace($dirPath, '', $fpath);
			$obj->text = $text;
			
			if(is_dir($fpath))
			{
				$obj->expanded = false;
				$obj->leaf = false;
			} 
			else
			{
				$obj->leaf = true;
			}
			$list[] = $obj;	
		}	
		Response::jsonArray($list);	
	}
	/**
	 * Create config subfolder
	 */
	public function fsmakedirAction()
	{
		
		$name = Request::post('name', 'string', '');
		$path = Request::post('path', 'string', '');
		
		$name = str_replace(array(DIRECTORY_SEPARATOR), '' , $name);
		
		if(!strlen($name))
			Response::jsonError($this->_lang->WRONG_REQUEST . ' [code 1]');
		
		$newPath = $this->_config->get('configs');
		
		if(strlen($path))
		{
			if(!is_dir($newPath. $path))
				Response::jsonError($this->_lang->WRONG_REQUEST  . ' [code 2]');
				
			$newPath.= $path . DIRECTORY_SEPARATOR;
		}
		 
		$newPath.= DIRECTORY_SEPARATOR . $name;			
			
		if(@mkdir($newPath, 0775))
			Response::jsonSuccess();
		else
			Response::jsonError($this->_lang->CANT_WRITE_FS);	
	}
	/**
	 * Create new report
	 */
	public function fsmakefileAction()
	{
		
		$name = Request::post('name', 'string', '');
		$path = Request::post('path', 'string', '');
		
		$name = str_replace(array(DIRECTORY_SEPARATOR), '' , $name);
		
		if(!strlen($name))
			Response::jsonError($this->_lang->WRONG_REQUEST . ' [code 1]');
		
		$newPath = $this->_config->get('configs');

		if(strlen($path))
			$filepath = $path . DIRECTORY_SEPARATOR . $name.'.designer.dat';
		else 
			$filepath = $name . '.designer.dat';
		
		if(file_exists($filepath))
			Response::jsonError($this->_lang->FILE_EXISTS);
		 		
		$obj = new Designer_Project();
		
		if($this->_storage->save($filepath, $obj))
			Response::jsonSuccess(array('file'=>$filepath));
		else
			Response::jsonError($this->_lang->CANT_WRITE_FS);	
	}
	
}